layui.use(['layer', 'laytpl', 'laypage'], function () {
    var $ = layui.jquery,
        layer = layui.layer,
        laypage = layui.laypage,
        laytpl = layui.laytpl;

    var count;     //每次获取的商品数
    var limit = 10;     //每页显示条目数
    var curPageGoods = {};
    var goods = {};
    var categories = {};
    var hash = "index.html#!goods/";

    $(document).ready( function () {
        $.ajax({
            url: "category.json",
            async: true,
            dataType: "json",
            success: function (data) {
                categories = data;
                renderLeftSide();
                addEventListener();
            }
        });
        getGoodsByCategory("newest");
    });

    function addEventListener() {
        var sideItem = $("li.left-side-item");

        sideItem.mouseover(function () {
            $(this).css("background-color", "#d2d2d2");
        });
        sideItem.mouseout(function () {
            $(this).css("background-color", "#FFFFFF");
        });
        sideItem.on("click", function () {
            var goodType = $(this).find("label").text();
            layer.load(1);
            getGoodsByCategory(goodType);
        });


    }

    Date.prototype.Format = function (format) {
        var o = {
            "M+": this.getMonth() + 1,
            "d+": this.getDate(),
            "H+": this.getHours(),
            "m+": this.getMinutes(),
            "s+": this.getSeconds(),
            "S+": this.getMilliseconds()
        };
        if (/(y+)/.test(format)) {
            format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            }
        }
        return format;
    };


   //分页选择页数 监听
    $('.sel').on("change", function () {
        paging(goods, 1);
        renderGoods(curPageGoods);
    });

    //处理页数与商品映射
    function paging(goods, pageNum) {
        pageNum = parseInt(pageNum);
        var singletonPageGoods = [];
        var start = (pageNum - 1) * limit;
        var end = (start + limit) > count ? count : start + limit;
        for (var i = start; i < end; i++) {
            singletonPageGoods[i - start] = JSON.stringify(goods.list[i]);
        }
        curPageGoods.list = JSON.parse('[' + singletonPageGoods.toString() + ']');
    }

    //异步渲染数据
    function renderGoods(data) {
        var getTpl = goodBoxTpl.innerHTML
            , view = document.getElementById('goods-list');
        laytpl(getTpl).render(data, function (html) {
            view.innerHTML = html;
        });
    }

    //分页
    function renderPages(count) {
        $('#all_number_sz').text(count);
        laypage.render({
            elem: 'sz_page_box',
            limit: limit,
            layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'],
            groups: 4,
            count: count, //从服务端取得,
            jump: function (obj, first) {
                limit = obj.limit;
                paging(goods, 1);
                if (!first) {
                    paging(goods, obj.curr);
                }
                renderGoods(curPageGoods);
            }
        });
    }

    //渲染左侧side
    function renderLeftSide() {
        console.log("come on");
        var getTpl = leftSideTpl.innerHTML,
            view = document.getElementById('left-side');
        laytpl(getTpl).render(categories, function (html) {
            view.innerHTML = html;
        });
    }

    //单张图片上传
    // function uploadImg() {
    //
    //     var uploadInst = upload.render({
    //         elem: '#uploadBtn'
    //         , url: '/api/publish.do'
    //         , auto: false
    //         , bindAction: '#submitBtn'
    //         , choose: function (obj) {
    //             obj.preview(function (index, file, result) {
    //                 $('#goodsImg').val(file.name);
    //             });
    //         }
    //         , done: function (res, index, upload) {
    //             //如果上传失败
    //             if (res.code > 0) {
    //                 return layer.msg('上传失败');
    //             }
    //             //上传成功
    //         }
    //         , error: function () {
    //             //失败状态，并实现重传
    //             var errText = $('#errText');
    //             errText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
    //             errText.find('.demo-reload').on('click', function () {
    //                 uploadInst.upload();
    //             });
    //         }
    //     });
    // }

    //添加图片路径前缀
    function addImgPrefix(prefix) {
        console.log(goods.list);
        console.log(prefix);
        for (var length = goods.list.length, i = 0; i < length; i++) {
            goods.list[i].src = prefix.toString() + goods.list[i].src;
            //去掉分号;
            goods.list[i].src = goods.list[i].src.substr(0, goods.list[i].src.length - 1);

            goods.list[i].pk_id = hash.toString() + goods.list[i].pk_id;

            // console.log(goods.list[i].src);
            // console.log(goods.list[i].pk_id);
        }
    }

    //根据种类获取商品
    function getGoodsByCategory(goodType) {
        if(goodType==="最新发布"){
            goodType = "newest";
        }
        var data = {};
        data.userId = localStorage.getItem("userId");
        $.ajax({
            url: "/api/goods/category/" + goodType,
            async: true,
            dataType: "json",
            timeout: 6000,
            success: function (ret) {
                if (ret.code === 0) {
                    layer.msg(ret.msg);
                    goods.list = ret.data;
                    goods.count = ret.data.length;
                    addImgPrefix(localStorage.getItem("prefix"));
                    console.log(goods);
                    count = goods.count;
                    $("h2").text(goodType==="newest"?"最新发布":goodType);//更新小标题
                    renderPages(goods.count);//分页
                    $('#sz_page_box').css("margin", "0 auto");
                    layer.msg("加载成功");
                }

                if (ret.code === -1) {
                    layer.msg(ret.msg());
                }

                if (ret.code === 2 || ret.code === 3) {
                    logout();
                }
                layer.closeAll();
            },
            error: function () {
                layer.closeAll('loading');
                layer.msg("加载失败");
            }
        });
    }

    function logout() {
        console.log("退出.........");
        localStorage.removeItem("prefix");
        localStorage.removeItem("userId");
        localStorage.removeItem("nickname");
        location.href = '/html/login.html'
    }
});